package xyz.chaobei.gateway3.outbound.client4;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

    private final boolean daemon;

    private final ThreadGroup group;

    private final String name;

    private final AtomicInteger threadNum = new AtomicInteger(1);

    public NamedThreadFactory(String name) {
        this(name, false);
    }

    public NamedThreadFactory(String name, boolean daemon) {
        this.daemon = daemon;
        SecurityManager securityManager = System.getSecurityManager();
        this.group = (securityManager != null) ? securityManager.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        this.name = name;
    }


    @Override
    public Thread newThread(Runnable r) {

        Thread t = new Thread(group, r, name + "-thread-" + threadNum.getAndIncrement(), 0);
        t.setDaemon(daemon);

        return t;
    }
}
